package cn.zhaozhiqi.consumer;

import cn.zhaozhiqi.constants.Constants;
import cn.zhaozhiqi.pojo.domain.Order;
import cn.zhaozhiqi.pojo.mq.dto.PayMQDto;
import cn.zhaozhiqi.service.IOrderService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@RocketMQMessageListener(
        //消费者的名字
        consumerGroup = "consumer-pay-success",
        //主题
        topic = Constants.Mq.TOPIC_PAY_SUCCESS,
        //tags
        selectorExpression = Constants.Mq.TAG_PAY_SUCCESS,
        //消息消费模式：默认是CLUSTERING集群，还支持BROADCASTING广播
        messageModel = MessageModel.BROADCASTING
)
public class PaySuccessOrderConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IOrderService orderService;

    @Override
    public void onMessage(MessageExt messageExt) {
        String jsonStr = new String(messageExt.getBody(), StandardCharsets.UTF_8);
        PayMQDto dto = JSON.parseObject(jsonStr, PayMQDto.class);
        //订单状态修改
        Order order = orderService.getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNo, dto.getOrderNo())
                .eq(Order::getStatus, Constants.OrderStatus.ORDER_STATUS_NOT_PAY));
        if (order == null){
            return;
        }
        order.setStatus(Constants.OrderStatus.ORDER_STATUS_PAYED);
        orderService.updateById(order);
    }
}
